< previous page page_165 next page >

Page 165
As you can see, the Else statement works as if you were talking to someone (that is, if the condition is true, then add the date, else if not, beep). With the Else statement you are testing for two conditions at the same time. But can you use the If-Then statement to test for multiple conditions? By using the ElseIf statement along with the rest of the If-Then-Else statements, you can test as many conditions as you need. This creates a section of code that is called a nested If statement. The following is the syntax of this extended version:
If condition Then
    [statements]
[Elself condition-n Then
    [elseifstatements] 
[Else
    [elsestatements]]
End If
You might notice from the preceding code snippet that the If-Then statements to be executed are indented. The reason for this becomes very clear as you start using this extended version of the statement. If all of the code was aligned to the left of the page, finding the matching If-ElseIf-Else-End If statements would be very difficult. If you lose track of the matching statements when you are coding the application, you could wind up having some sections of code execute incorrectly. Many programmers use the If statement to test a variable that has been modified just before the If statement itself, as shown here:
RetCode = MsgBox(Okay to Delete Record, vbQuestion + vbOKCancel, App.Title)
If (RetCode = vbOK) Then
    Perform delete code
End If
You have just seen in the previous sections in this chapter that you can use the MsgBox to return a value directly into an expression, so this code can be rewritten as
If (MsgBox(Okay to Delete Record, vbQuestion + vbOKCancel, App.Title) _
   = vbOK) Then
    Perform delete code
End If
There is no limit to the number of nested If statements that you can string together. However, there is a mental limit. You do not want to create so complex a section of code that you cannot figure out what it does. There are other ways to create a conditional test block for many different cases.
Before leaving the If-Then statement, look at some of the other ways it can be used. You probably know that you can code an If-Then statement on one line if only one code statement must be executed. For example:
If the sale was over $500 give a 10% discount

 
< previous page page_165 next page >

If you like this book, buy it!